# Standalone Torrent Auditor
#
import math

pieces=[];

def initFile(torrent):
	global pieces;
	fileinfo = torrent['info'];
	totallength=0;
	if 'length' in fileinfo:
		totallength=fileinfo['length']
	else:
		for key in fileinfo['files']:
			totallength += key['length'];
	pieces['data'] = "";
	pieces['verified'] = [0]*math.ceil(totallength*1.0/piecelength)
	pieces['hash'] = [0]*math.ceil(totallength*1.0/piecelength)
	for i in range(len(pieces['hash'])):
		pieces['hash'][i] = fileinfo['pieces'][0:20];
		fileinfo['pieces'] = fileinfo['pieces'][20:];
	
	pieces['pl'] = fileinfo['piece length'];
	pieces['length'] = totallength;
	pieces['name'] = fileinfo['name']

def getStatus():
	global pieces;
	return float(sum(pieces['verified'])) / len(pieces['verified']);

def getNextOffset():
	global pieces;
	pl = pieces['pl'];
	l = len(pieces['data']);
	p = l/pl;
	o = l%pl;
	return (p,o);

def saveData(data,(i,o)):
	global pieces;
	offset = pieces['pl']*i+o;
	olen = len(pieces['data']);
	l = len(data);
	pieces['data'][offset:offset+l] = data;
	#check to see if we can verify / kill more pieces
	nlen = len(pieces['data']);
	v = (offset+l)/pieces['pl'] - 1;
	if nlen==pieces['length']:
		verifyData();
	elif v>=0 and not pieces['verified'][v]:
		verifyData();

def verifyData():
	ld = len(pieces['data']);
	tl = pieces['length']
	pl = pieces['pl']
	for i in range(len(pieces['hash'])):
		if not pieces['verified'][i] and (ld >= i * pl or ld == tl):
			piece = pieces['data'][i*pl:i*(pl+1)];
			sha = hashlib.sha1(piece).digest();
			if sha == pieces['hash'][i]:
				pieces['verified'][i] = 1
			else:
				pieces['data'] = pieces['data'][0:i*pl]
				ld = len(pieces['data']);

def finishData():
	global pieces;
	FILE = open(pieces['name'],"w");
	FILE.write(pieces['data']);
	FILE.close();